
# analyze national institute for money in state politics data
library(ggplot2)
library(dplyr)
library(reshape2)

setwd("~/Dropbox/Project_fundraising/dataverse/")
dat = read.csv("Original Data/FollowTheMoneyDownload20180319(040359).csv")
names(dat) = tolower(names(dat))

dat = dat %>% 
  rename(year = election_year,state = election_jurisdiction, tot = total_.) 

dat = dat %>% 
  filter(incumbency_status %in% c("Open", "Challenger"),
         election_status == "Won-General", 
         year >= 2012) %>% 
  mutate(type = ifelse(grepl("SENATE", office_sought), "Upper Chamber", "Lower Chamber"))
  

statesum = dat %>% 
  group_by(state, type) %>% 
  summarise(mean = mean(tot), 
            q25 = quantile(tot, .25),
            median = median(tot),
            q75 = quantile(tot, .75)) %>% 
  arrange(mean) %>% 
  ungroup() %>% 
  mutate(state = factor(state, unique(state))) 

statesumsum = statesum %>% 
  group_by(type) %>% 
  summarise(q25 = quantile(mean, .25),
            q5 = quantile(mean, .5),
            q75 = quantile(mean, .75)) %>% 
  ungroup()

ggplot(statesum) + 
  aes(x = state, y = mean) + 
  geom_bar(stat = "identity") + 
  geom_hline(yintercept = 25000) +
  geom_hline(yintercept = 100000) +
  geom_hline(yintercept = 300000) +
  coord_flip() + 
  facet_wrap(~type, scales = "free_x") + 
  scale_y_continuous(labels = function(x) paste0("$", prettyNum(x / 1000, big.mark = ","))) + 
  labs(x = NULL, y = "Average fundraising of successful challengers, 2012-2017 (thousands)") + 
  theme_minimal() + 
  theme(panel.grid = element_blank(), 
        panel.spacing = unit(0, "in"))
ggsave("figs/nimsp_fundraising.pdf",width=6,height=6)


ggplot(filter(statesum, type == "Lower Chamber")) + 
  aes(x = state, y = mean) + 
  geom_bar(stat = "identity") + 
  geom_hline(yintercept = 25000) +
  geom_hline(yintercept = 100000) +
  geom_hline(yintercept = 300000) +
  coord_flip() + 
  scale_y_continuous(labels = function(x) paste0("$", prettyNum(x / 1000, big.mark = ","))) + 
  labs(x = NULL, y = "Fundraising of successful challengers, 2012-2017 (thousands)") + 
  theme_minimal() + 
  theme(panel.grid = element_blank(), 
        panel.spacing = unit(0, "in"),
        text = element_text(size = 14))
ggsave("figs/nimsp_fundraising_lower.pdf",width=6,height=8)





